<?php

namespace app\common\model\shop;

use addons\leescore\model\Address;
use app\admin\model\Leeaddress;
use app\common\model\Area;
use app\common\utils\Utils;
use think\Db;
use think\exception\ValidateException;
use think\Model;
use traits\model\SoftDelete;

class Order extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'shop_order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'type_text',
        'address_text',
        'createtime_text'
    ];

    protected static function init()
    {
        Order::beforeInsert(function ($order) {
            $address = Leeaddress::get($order['address_id']);
            $order['province'] = $address['province'];
            $order['city'] = $address['city'];
            $order['area'] = $address['area'];
            $order['address'] = $address['address'];
            //插入订单前扣除库存
            $num = $order['num'];
            $goods = Goods::get($order['goods_id']);

            if ($goods['stock'] < $num && $order['use_time'] == 0) {
                throw new ValidateException('库存不足');
            }
            if (!$goods) {
                throw new ValidateException('牛商品不存在');
            }
            if ($goods['type'] == 1) {
                //成交金额
                $order['money'] = Utils::processMoney($num, $goods['money'], '*', 2);
            }
            //计算成交金额
            //增加销量
            Goods::where(['id' => $order['goods_id']])->setInc('sales', $num);
            if ( $order['use_time'] == 0) {
                //扣除
                Goods::where(['id' => $order['goods_id']])->setDec('stock', $num);
            }
        });

        Order::beforeUpdate(function ($order) {
            $address = Leeaddress::get($order['address_id']);
            $order['province'] = $address['province'];
            $order['city'] = $address['city'];
            $order['area'] = $address['area'];
            $order['address'] = $address['address'];
            $orderOrigin = Order::get($order['id']);
            $goods = Goods::get($order['goods_id']);
            if (!$goods) {
                throw new ValidateException('商品被删除');
            }
            if (!$orderOrigin) {
                throw new ValidateException('订单不存在');
            }
            $goods = Goods::get($order['goods_id']);

            if ($order['num'] < $orderOrigin['num']) {
                $add = $orderOrigin['num'] - $order['num'];
                if ($goods['stock'] < $add) {
                    throw new ValidateException('库存不足');
                }

                //计算成交金额
                //增加销量
                Goods::where(['id' => $order['goods_id']])->setInc('sales', $add);
                if ( $order['use_time'] == 0) {
                    //扣除
                    Goods::where(['id' => $order['goods_id']])->setDec('stock', $add);
                }

            } else if ($order['num'] > $orderOrigin['num']) {
                $cuadd = $order['num']  - $orderOrigin['num'];
                Goods::where(['id' => $order['goods_id']])->setDec('sales', $cuadd);
                if ( $order['use_time'] = 0) {
                    //扣除
                    Goods::where(['id' => $order['goods_id']])->setDec('stock', $cuadd);
                }

            }


            if ($goods['type'] == 1) {
                //成交金额
                $order['money'] = Utils::processMoney($order['num'], $goods['money'], '*', 2);
            }
        });

    }

    
    public function getTypeList()
    {
        return ['0' => '待处理', '1' => '已安排', '2' => '拒绝', '3'=> '待定'];
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();

        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return Utils::time_format($value, $style='Y-m-d H:i:s');
    }

    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function goods()
    {
        return $this->belongsTo('app\common\model\shop\Goods', 'goods_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function getAddressTextAttr($value, $data)
    {
        $province = $data['province'];
        $city = $data['city'];
        $area = $data['area'];
        $address = $data['address'];
        $arr = [$province, $city, $area];
        $values = Area::where(['id' => ['in', $arr]])->order('id asc')->column('name', 'id');
        $str = Utils::implodeArr($values, '');

        return $str . '' . $address;
    }

    public function getMoneyAttr($value, $data) {
        $value = $value ? $value : (isset($data['money']) ? $data['money'] : '');

        if (floatval($value) <= 0) {
            return '暂未定价';
        }

        return $value;
    }



}
